package com.ruoyi.mysystem.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.mysystem.service.SendMailService;
import com.ruoyi.mysystem.util.EmailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;


@Service
public class SendMailServiceImpl implements SendMailService {

    @Autowired
    private EmailUtils emailUtils;

    @Autowired
    private RedisCache redisCache;

    private static final Map<String, Long> CODE_MAP = new ConcurrentHashMap();

    @Override
    public void SendMail(String email, String type) {
        String  code = RandomUtil.randomNumbers(6);
        String context = "<b>尊敬的用户：</b><br><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好，" +
            "寻惠平台提醒您本次的验证码是：<b>{}</b>，" +
            "有效期5分钟。<br><br><br><b>寻惠</b>";
        String html = StrUtil.format(context, code);
        if ("register".equals(type)) {
            // 多线程异步请求
            ThreadUtil.execAsync(() -> {
                emailUtils.sendHtml("【寻惠平台】邮箱验证",html, email);
                redisCache.setCacheObject("emailCode_"+email,code, 5,TimeUnit.MINUTES);
            });
            CODE_MAP.put(code, System.currentTimeMillis());
        }
    }

    @Override
    public void SendMail(String email, String type, String code) {
        String context = "<b>尊敬的用户：</b><br><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好，" +
            "FunnyTrip提醒您本次的验证码是：<b>{}</b>，" +
            "有效期5分钟。<br><br><br><b>畅途</b>";
        String html = StrUtil.format(context, code);
        if ("register".equals(type)) {
            // 多线程异步请求
            ThreadUtil.execAsync(() -> {
                emailUtils.sendHtml("【FunnyTrip】邮箱验证",html, email);
            });
            CODE_MAP.put(code, System.currentTimeMillis());
        }
    }
}
